package com.crawling.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.config.RequestConfig.Builder;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import java.io.File;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.security.GeneralSecurityException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 封装了采用HttpClient发送HTTP请求的方法
 *
 * @author lilin
 * @create 2016年10月12日18:52:06
 * @see //本工具所采用的是HttpComponents-Client-4.3.2
 * @see ========================================================================
 * == =========================
 * @see //sendPostSSLRequest 发送https post请求，  兼容 http post 请求
 * @see //sendGetSSLRequest  发送https get请求，  兼容 http get 请求
 */
@Slf4j
public class HttpClientUtil {


    public static final String msg = "通信失败";
    public static final String download = "图片下载失败";
    /**
     * 连接超时
     */
    public static final int connTimeout = 4 * 1000;
    /**
     * 响应超时
     */
    public static final int socketTimeout = 18 * 1000;
    /**
     * 响应超时
     */
    public static final int requestTimeout = 5000;

    private static ReentrantLock lockDownLoad = new ReentrantLock(); //原来下载图片或者get 请求超时 加锁 但是速度太慢了
    private static ReentrantLock lockGetHttp = new ReentrantLock();

    /**
     * 默认字符编码
     */
    public static final String charset = "UTF-8";
    private static CloseableHttpClient client;

    static {
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        cm.setMaxTotal(100000);
        cm.setDefaultMaxPerRoute(80000);

        client = HttpClients.custom().setConnectionManager(cm).build();
        new IdleConnectionEvictor(cm).start();
    }


    public static class IdleConnectionEvictor extends Thread {

        private final HttpClientConnectionManager connMgr;

        private volatile boolean shutdown;

        public IdleConnectionEvictor(HttpClientConnectionManager connMgr) {
            this.connMgr = connMgr;
        }

        @Override
        public void run() {
            try {
                while (!shutdown) {
                    synchronized (this) {
                        wait(2000);
                        // 关闭失效的连接
                        connMgr.closeExpiredConnections();
                    }
                }
            } catch (InterruptedException ex) {
                // 结束
            }
        }

        public void shutdown() {
            shutdown = true;
            synchronized (this) {
                notifyAll();
            }
        }
    }


    public static String get(String url) {
        return sendGetSSLRequest(url, charset);
    }

    public String get(String url, String charset) {
        return sendGetSSLRequest(url, charset);
    }


    /**
     * 发送一个 GET 请求
     *
     * @param url
     * @param charset
     * @param //connTimeout 建立链接超时时间,毫秒.
     * @param //readTimeout 响应超时时间,毫秒.
     * @return
     * @throws ConnectTimeoutException 建立链接超时
     * @throws SocketTimeoutException  响应超时
     * @throws Exception
     */

    public static String sendGetSSLRequest(String url, String charset) {
        long startTime = System.nanoTime();
        CloseableHttpClient client = null;
        String result = msg;
        HttpGet get = new HttpGet(url);
        try {
            // 设置参数
            Builder customReqConf = RequestConfig.custom();
            customReqConf.setConnectTimeout(connTimeout);
            customReqConf.setSocketTimeout(socketTimeout);
            customReqConf.setConnectionRequestTimeout(requestTimeout);

            get.setConfig(customReqConf.build());
            get.addHeader("Connection", "Close");
            HttpResponse res;

            // 执行 Http 请求.
            if (url.startsWith("https")) {
                // 执行 Https 请求.
                client = createSSLInsecureClient();
                res = client.execute(get);
            } else {
                // 执行 Http 请求.
                client = HttpClientUtil.client;
                res = client.execute(get);
            }

            return EntityUtils.toString(res.getEntity(), charset);
        } catch (Exception e) {
            log.error("执行http请求  url:{} SocketTimeoutException 异常{}", url, e);
        } finally {
            log.info("HTTP get 请求执行时间: {}  ===> url : {}", (System.nanoTime() - startTime), url);
            get.releaseConnection();
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        log.error("请求网址 get 失败： {}", url);
        return result;
    }


    /**
     * 下载文件
     *
     * @param url     文件url
     * @param fileUrl 目标目录
     * @throws Exception
     */

    public static String downloadFile(String url, String fileUrl, String... down) {
        if (down.length < 1) {
            return "图片下载成功";
        }
        long startTime = System.nanoTime();
        System.out.println("<================================图片下载 HTTP GET 请求 url:" + url + " ===========================>");
        CloseableHttpClient client = null;
        String result = download;
        HttpGet get = new HttpGet(url);
        try {
            Builder customReqConf = RequestConfig.custom();
            customReqConf.setConnectTimeout(connTimeout);
            customReqConf.setSocketTimeout(socketTimeout);
            customReqConf.setConnectionRequestTimeout(requestTimeout);

            get.setConfig(customReqConf.build());
            get.addHeader("Connection", "Close");
            HttpResponse res = null;

            // 执行 Http 请求.
            if (url.startsWith("https")) {
                // 执行 Https 请求.
                client = createSSLInsecureClient();
                res = client.execute(get);
            } else {
                // 执行 Http 请求.
                client = HttpClientUtil.client;
                res = client.execute(get);
            }
            FileUtils.writeByteArrayToFile(new File(fileUrl), IOUtils.toByteArray(res.getEntity().getContent()));
            log.info("图片下载成功：url  {}", url);
            return "图片下载成功";

        } catch (Exception e) {
            log.error("图片下载失败 SocketTimeoutException 异常信息 {}", e);
        } finally {
            log.info("图片下载执行时间: {} 秒===> url : {}", (System.nanoTime() - startTime) / (1000000000), url);
            get.releaseConnection();
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        log.error("图片下载失败： url :{}", url);
        return result;
    }


    public static byte[] downloadFileByte(String url) {
        long startTime = System.nanoTime();
        System.out.println("<================================图片下载 HTTP GET 请求 url:" + url + " ===========================>");
        CloseableHttpClient client = null;
        String result = download;
        HttpGet get = new HttpGet(url);
        try {
            Builder customReqConf = RequestConfig.custom();
            customReqConf.setConnectTimeout(connTimeout);
            customReqConf.setSocketTimeout(socketTimeout);
            customReqConf.setConnectionRequestTimeout(requestTimeout);

            get.setConfig(customReqConf.build());
            get.addHeader("Connection", "Close");
            HttpResponse res = null;

            // 执行 Http 请求.
            if (url.startsWith("https")) {
                // 执行 Https 请求.
                client = createSSLInsecureClient();
                res = client.execute(get);
            } else {
                // 执行 Http 请求.
                client = HttpClientUtil.client;
                res = client.execute(get);
            }
            return IOUtils.toByteArray(res.getEntity().getContent());

        } catch (Exception e) {
            log.error("图片下载失败 SocketTimeoutException 异常信息 {}", e);
        } finally {
            log.info("图片下载执行时间: {} 秒===> url : {}", (System.nanoTime() - startTime) / (1000000000), url);
            get.releaseConnection();
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        log.error("图片下载失败： url :{}", url);
        return new byte[0];
    }


    private static ReentrantLock lockGetResponseArry = new ReentrantLock();

    public static byte[] getSSLResponseByte(String url) {
        HttpGet get = new HttpGet(url);
        CloseableHttpClient client = null;

        long startTime = System.nanoTime();

        try {
            //lockGetHttp.lock();
            // 设置参数
            Builder customReqConf = RequestConfig.custom();
            customReqConf.setConnectTimeout(connTimeout);
            customReqConf.setSocketTimeout(socketTimeout);
            customReqConf.setConnectionRequestTimeout(requestTimeout);

            get.setConfig(customReqConf.build());
            get.addHeader("Connection", "Close");
            HttpResponse res = null;


            // 执行 Http 请求.
            if (url.startsWith("https")) {
                // 执行 Https 请求.
                client = createSSLInsecureClient();
                res = client.execute(get);
            } else {
                // 执行 Http 请求.
                client = HttpClientUtil.client;
                res = client.execute(get);
            }
            return IOUtils.toByteArray(res.getEntity().getContent());

        } catch (Exception e) {

            // 打印完整错误信息
            e.printStackTrace();
            log.error("获取response arr 请求  url:{} SocketTimeoutException 异常{}", url, e);

        } finally {

            log.info("获取response arr 请求执行时间: {} 秒 ===> url : {}", (System.nanoTime() - startTime) / (1000 * 1000 * 1000), url);
            get.releaseConnection();
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        log.error("获取response arr 失败： {}", url);
        return null;

    }


    public static void main(String[] args) {
//        StopWatch w = new StopWatch();
//        w.start();
//
//        w.stop();
//        System.err.println(w.getTime());


    }


    /**
     * 创建 SSL连接
     *
     * @return
     * @throws GeneralSecurityException
     */
    private static CloseableHttpClient createSSLInsecureClient() throws GeneralSecurityException {
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            }).build();

            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() {

                @Override
                public boolean verify(String arg0, SSLSession arg1) {
                    return true;
                }

                @Override
                public void verify(String host, SSLSocket ssl)
                        throws IOException {
                }

                @Override
                public void verify(String host, X509Certificate cert)
                        throws SSLException {
                }

                @Override
                public void verify(String host, String[] cns,
                                   String[] subjectAlts) throws SSLException {
                }

            });

            return HttpClients.custom().setSSLSocketFactory(sslsf).build();

        } catch (GeneralSecurityException e) {
            throw e;
        }
    }
}